<!-- 费用审核 项目内的费用审核 -->
<template>
  <div>
    <a-descriptions title="费用审核"></a-descriptions>
    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      bordered
      :columns="columns"
      :data="loadData"
      class="clear-padding"
      @change="handleTableChange"
    >
      <template slot="title">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="8" :sm="24">
                <a-form-item label="申请单号">
                  <a-input v-model="queryParam.applyNo" placeholder="请输入" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="申请类型">
                  <a-select v-model="queryParam.type" placeholder="请选择" default-value="0" allowClear>
                    <a-select-option
                      v-for="item in $const.SUBJECTANDREESA"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.desc }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <template v-if="advanced">
                <a-col :md="8" :sm="24">
                  <a-form-item label="申请者ID">
                    <a-input v-model="queryParam.createrId" placeholder="请输入" />
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-model-item label="发起日期:" labelAlign="left">
                    <a-range-picker @change="handleSelectDate" v-model="queryDate" allowClear />
                  </a-form-model-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="收款人编号" v-if="queryParam.type">
                    <a-input v-model="queryParam.userNo" placeholder="请输入" />
                  </a-form-item>
                </a-col>
              </template>
              <a-col :md="8" :sm="24">
                <span
                  class="table-page-search-submitButtons"
                  :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
                >
                  <a-button type="primary" @click="searchTable">查询</a-button>
                  <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                  <a-button style="margin-left: 8px" :loading="exporting" icon="export" @click="clickExport" v-if="$auth('FEE_REVIEW.FEE_REVIEW_EXPORT')">导出</a-button>

                  <a @click="toggleAdvanced" style="margin-left: 8px">
                    {{ advanced ? '收起' : '展开' }}
                    <a-icon :type="advanced ? 'up' : 'down'" />
                  </a>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- tab 切换 start -->
        <a-tabs @change="handleTab">
          <template v-for="(list, i) in tabs">
            <a-tab-pane :tab="list.desc" :key="i"></a-tab-pane>
          </template>
        </a-tabs>
        <!-- tab 切换  end -->
      </template>
      <template slot="status" slot-scope="text, record">
        {{ record.status | enumValueByKey($const.EXAMINE_TYPE) }}
      </template>
      <template slot="createTime" slot-scope="text">
        <span v-if="text">{{ text | moment() }}</span>
      </template>
      <template slot="ptsNo" slot-scope="text, record">
        {{ record.type == $const.SUBJECTANDREESA.DAISHENGPI.value ? record.researchDetailNo : text }}
      </template>
      <template slot="type" slot-scope="text, record">
        {{ record.type | enumValueByKey($const.SUBJECTANDREESA) }}
      </template>
      <template slot="operation" slot-scope="text, record">
        <a @click="clickView(record)" v-if="$auth('FEE_REVIEW.FEE_REVIEW_DETAIL')">查看</a>
      </template>
    </s-table>
    <DetailView
      @closeCallback="closeCallback"
      @openPopup="openPopup"
      @payRecord="payRecord"
      @refresh="refreshTable"
      ref="detailView"
      :visible="visible"
      :info="{ name: 'xiaopang' }"
      :costId="costId"
      :thisStatus="thisStatus"
    ></DetailView>
    <AuditFailure
      :visible="visibles"
      @uploadModalCancel="uploadModalCancel"
      @uploadClickConfirm="uploadClickConfirm"
      :auditStatus="auditStatus"
      ref="AuditFailure"
    >
    </AuditFailure>
    <Approve
      :oveVisibles="oveVisibles"
      @uploadModalCancel="uploadModalCancel"
      :auditStatus="auditStatus"
      @roveModalCancel="roveModalCancel"
      ref="Approve"
    >
    </Approve>
  </div>
</template>
<script>
import storage from 'store'
import { CURRENT_PROJECT } from '@/store/mutation-types'

import monitor from '@/utils/monitor'
import costAuditing from '@/monitor/views/cost-auditing/index'

import { processListAudit, switchAudit, applyTax, getCostExport, costRecordPay } from '@/api/cost/audit'
import DetailView from '@/views/cost-auditing/detail.vue'
import AuditFailure from '@/views/cost-auditing/components/auditFailure'
import Approve from '@/views/cost-auditing/components/approve'
import { FINANCE_STATUS, APPLIER_STATUS } from '@/constants/common'
import { buildPaginationObj } from '@/components/Table'
import { exportExcel } from '@/utils/util'
import { columns } from './config'

const watch = monitor(costAuditing)
export default {
  props: {},
  components: {
    DetailView,
    AuditFailure,
    Approve
  },
  computed: {
    tabs () {
      if (this.$store.state.user.roles[0].code === 'SYS_FINANCE') {
        return FINANCE_STATUS
      }
      return APPLIER_STATUS
    }
  },
  data () {
    return {
      // tab切换
      tabsKey: null,
      visible: false,
      visibles: false,
      oveVisibles: false,
      detailInfo: {},
      queryParam: {
        proId: this.$route.query.id
      },
      costId: 0,
      queryDate: [],
      loadData: (parameter) => {
        if (this.$auth('FEE_REVIEW.FEE_REVIEW_LIST')) {
          if (this.$route.query.id) {
            const userNoParams = {}
            if (this.queryParam.userNo) {
              if (this.queryParam.type === this.$const.SUBJECTANDREESA.DAISHENGPI.value) {
                userNoParams.researchDetailNo = this.queryParam.userNo
              } else {
                userNoParams.ptsNo = this.queryParam.userNo
              }
            }
            this.queryParam.proId = this.$route.query.id
            return processListAudit(Object.assign({ status: this.tabsKey }, parameter, this.queryParam, userNoParams))
              .then((res) => {
                this.pageSize = res.totalCount
                return res
              })
              .catch(() => {})
           }
        } else {
          return Promise.resolve(buildPaginationObj([]))
        }
      },
      advanced: false,
      thisStatus: '',
      columns,
      pageSize: null,
      auditStatus: {}, // 审核弹窗审核状态
      exporting: false
    }
  },
  mounted () {
    this.approvalCost()
  },
  created () {
    this.tabsKey = this.tabs[0].value
    // 设置项目id
    const pro = storage.get(CURRENT_PROJECT)
    if (pro != null && pro.length > 0) {
      const project = JSON.parse(pro)
      this.$route.query.id = project.id
    }
  },
  methods: watch({
    // 用于切换tab状态的
    handleTab (key) {
      this.approvalCost()
      this.tabsKey = this.tabs[key].value
      this.queryParam = {
        proId: this.$route.query.id
      }
      this.queryDate = []
      this.$refs.table.refresh(true)
    },
    // 点击展开 详细搜索信息
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    // 点击重置
    reset () {
      this.queryParam = {
        proId: this.$route.query.id
      }
      this.queryDate = []
      this.$refs.table.refresh(true)
    },
    // 点击查看
    clickView (record) {
      this.costId = record.id
      this.thisStatus = record.status
      this.visible = true
      this.clickViewPoint()
    },
    clickEdit (record) {
      console.log('点击编辑', record)
      // this.$router.push({ name: 'EditResearcher', query: { ...record } })
    },
    // 处理发起日期选择框改变时产生的回调
    handleSelectDate (date, dateString) {
      this.queryDate = date
      this.queryParam.applyStartTime = dateString[0]
      this.queryParam.applyEndTime = dateString[1]
      console.log(date, dateString, '打印Date')
    },
    // 点击查询
    searchTable () {
      this.$refs.table.refresh(true)
    },
    // 点击查询
    refreshTable () {
      this.$refs.table.refresh()
    },
    // 弹窗关闭回调
    closeCallback () {
      this.visible = false
    },
    // 审核弹窗关闭回调
    uploadModalCancel () {
      this.visibles = false
      this.oveVisibles = false
    },
    // 审核弹窗确认回调
    uploadClickConfirm (value) {
      const status = value.status === true ? 1 : -1
      if (status === 1) {
        this.clickAgree() // 费用审核点击同意埋点
      } else {
        this.clickReject() // 费用审核点击驳回埋点
      }
      this.$refs.AuditFailure.confirmLoading = true
      switchAudit({ id: value.id, status: status, refuseReason: value.refuseReason })
        .then((res) => {
          console.log(res)
          this.$refs.AuditFailure.confirmLoading = false
          this.$refs.AuditFailure.form = {}
          this.$message.success('操作成功')
          this.closeCallback()
          this.uploadModalCancel()
          this.$refs.table.refresh()
          // 中央事件总线 通知研究者/受试者费用申请列表及时刷新
          this.$globalVue.$emit('approvalCostUpdate')
        })
        .catch(() => {
          this.$refs.AuditFailure.confirmLoading = false
        })
    },
    // 打开审核弹窗
    openPopup (value) {
      if (value.status === 1) {
        // debugger
        this.auditStatus = value
        this.oveVisibles = true
        return
      }
      this.auditStatus = value
      console.log(value, '***************************')
      this.visibles = true
    },
    // 个税凭证确认
    roveModalCancel (value) {
      this.$refs.Approve.confirmLoading = true
      this.clickPersonTax() // 费用审核点击个税办理埋点
      applyTax({ ...value })
        .then((res) => {
          this.$refs.Approve.confirmLoading = false
          this.$message.success('操作成功')
          this.closeCallback()
          this.uploadModalCancel()
          this.$refs.table.refresh()
        })
        .catch(() => {
          this.$refs.Approve.confirmLoading = false
        })
    },
    clickExport () {
      const params = { ...this.queryParam, status: this.tabsKey }
      if (this.queryParam.userNo) {
        if (this.queryParam.type === this.$const.SUBJECTANDREESA.DAISHENGPI.value) {
          params.researchDetailNo = this.queryParam.userNo
        } else {
          params.ptsNo = this.queryParam.userNo
        }
      }
      this.exporting = true
      params.pageSize = this.pageSize
      getCostExport(params).then(res => {
        this.exporting = false
        exportExcel('费用审核', res)
      }).catch(_ => {
        this.exporting = false
      })
    },
    // 费用审核页面浏览埋点
    approvalCost () {},
    // 点击查看埋点
    clickViewPoint () {},
    // 费用审核点击同意埋点
    clickAgree () {},
    // 费用审核点击驳回埋点
    clickReject () {},
    // 费用审核点击个税办理埋点
    clickPersonTax () {},
    payRecord () {
      console.log('123213', this.costId, costRecordPay)
      this.$refs.detailView.payLoading = true
      costRecordPay({ id: this.costId }).then(res => {
        this.$refs.detailView.payLoading = false
        this.$message.success('操作成功')
        this.closeCallback()
        this.uploadModalCancel()
        this.$refs.table.refresh()
      }).catch(_ => {
        this.$refs.detailView.payLoading = false
      })
    },
    // 点击排序
    handleTableChange (pagination, filters, sorter) {
      console.log(sorter, '排序参数')
    }
  })
}
</script>
